const cheerio = require('cheerio')
const superagent = require('superagent')
const FakeUseragent = require('fake-useragent')

// 根据歌曲详情页面获取百度网盘地址和密码
function getMusicInfo(url) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            superagent.get(url).set('User-Agent', FakeUseragent()).end((err, res) => {
                if (err) {
                    console.log('歌曲不存在')
                    return
                }
                let $2 = cheerio.load(res.text)
                let code = $2('b.mt_1.yh.d_b').text()
                resolve({
                    panUrl: $2('div.fl.over>a').attr('href'),
                    code: code.slice(code.search('：') + 1)
                })
            })
        }, 500)
    })
}

// 获取歌手某一页的歌曲列表
async function getMusicFromSingerPage(htmlStr) {
    let songsList = []
    let $ = cheerio.load(htmlStr.text)
    $('div.news.w310 ul.mt_05 li a').each((i, el) => {
        let music = {
            name: $(el).text(),
            url: $(el).attr('href')
        }
        songsList.push(music)
    })

    for (let i = 0, len = songsList.length; i < len; i++) {
        songsList[i].info = await getMusicInfo(songsList[i].url)
    }

    // 歌手某一页的歌曲列表  
    return songsList
}

// 获取歌手列表
function getArtistList(htmlStr) {
    let artistList = {}
    let $ = cheerio.load(htmlStr)
    $('body > div.bg_wh.all.m > div > div.fl.over.w638 > div.n_one.mt_1.pad_b_10').each((i, el) => {
        let a = $('h2', el).text()
        artistList[a] = {}
        $('div.ml_1.w610.over > div.gs_a', el).each((j, el) => {
            let spanLen = $('span', el).text().length
            let singer = ''
            let artist = {
                id: i * 10 + j
            }
            if (spanLen > 0) {
                singer = $('a', el).text().slice(spanLen)
                artist.hasHome = 0
                artist.songsListPage = `http://www.51ape.com/skin/ape/php/qx_2.php?qx=${singer}`
                artistList[a][singer] = artist
            } else {
                singer = $('a', el).text()
                artist.hasHome = 1
                artist.homePage = $('a', el).attr('href')
                artistList[a][singer] = artist
            }
        })
    })
    return artistList
}

// 获取单页歌手的歌曲信息
async function getSingleSingerMusicList(htmlStr) {
    let $ = cheerio.load(htmlStr)
    let res = []
    $('body > div.w260.wd.m.mt_1.over > li').each((i, el) => {
        let target = $('a', el).text()
        res.push({
            url: $('a', el).attr('href'),
            name: target.slice(target.lastIndexOf('-') + 2),
            info: {}
        })
    })

    for (let i = 0, len = res.length; i < len; i++) {
        res[i].info = await getMusicInfo(res[i].url)
        delete res[i].url
    }

    return res
}

// 获取歌手主页的歌曲信息
async function getSinglePageMusicList(htmlStr, url) {
    let $ = cheerio.load(htmlStr)
    // 获取最大页码
    let maxPageStr = $('body > div.bg_wh.all.m > div > div.fl.over.w638 > div.fl.over.w638.mt_2 > div.mt_1.listpage.b_t_d.b_b_d.lh50 > a:last-child').attr('href') || '1'
    let maxPage = maxPageStr.match(/(?<=index\_)[0-9]*(?=\.html)/)
    maxPage = maxPage !== null ? maxPage[0] : 1
    let songsListHtmlStr = []
    for (let i = 1; i <= parseInt(maxPage); i++) {
        let requestUrl
        if (i === 1) {
            requestUrl = url
        } else {
            requestUrl = 'http://www.51ape.com' + maxPageStr.replace(/(?<=index\_)[0-9]*(?=\.html)/, i)
        }

        superagent.get(requestUrl).set('User-Agent', FakeUseragent()).end((err, res) => {
            if (err) {
                throw Error('err')
            }
            songsListHtmlStr.push(res)
        })

    }

    let songsList = []
    for (let i = 0, len = songsListHtmlStr.length; i < len; ++i) {
        let data = await getMusicFromSingerPage(songsdataHtmlStr[i])
        songsList.push(data)
        console.log(`${i}/${parseInt(maxPage)}`)
    }
    console.log(songsList)
    return songsList
}


module.exports = {
    getMusicFromSingerPage,
    getMusicInfo,
    getArtistList,
    getSingleSingerMusicList,
    getSinglePageMusicList
}